$(function () {

    var bill_datagrid = $("#bill_datagrid");
    var bill_dialog = $("#bill_dialog");

    //部门列表初始化-begin
    $("#bill_datagrid").datagrid({
        fit: true,
        url: "/orderBill/list",
        fitColumns: true,
        pagination: true,
        rownumbers: true,
        singleSelect: true,
        striped: true,
        toolbar: "#tb",
        columns: [[
            {field: "ck", checkbox: true},  //显示多选框样式
            {field: "id", title: "编号", hidden: true},
            {field: "sn", title: "订单编码", width: 100},
            {field: "vdate", title: "业务时间", width: 100, sortable: true, order: 'desc'},
            {
                field: "status", title: "状态", width: 100, formatter: function (value, row, index) {
                if (value == 1) {
                    return "<font color='green'>已审核</font>"
                } else if (value == 0) {
                    return "<font color='red'>未审核</font>"
                }
            }
            },
            {field: "totalAmount", title: "总金额", width: 100},
            {field: "totalNumber", title: "总数量", width: 100},
            {field: "auditTime", title: "审核时间", width: 100, sortable: true, order: 'desc'},
            {field: "inputTime", title: "录入时间", width: 100, sortable: true, order: 'desc'},
            {
                field: "inputUser", title: "录入人", width: 100, formatter: function (value) {
                return value ? value.username : "";
            }
            },
            {
                field: "auditor", title: "审核人", width: 100, formatter: function (value) {
                return value ? value.username : "";
            }
            },
            {
                field: "supplier", title: "供应商", width: 100, formatter: function (value) {
                return value ? value.name : "";
            }
            },
            {
                field: "operation", title: "操作", width: 100, formatter: function (value, row, index) {
                if (row.status == 1) {
                    var str = '<a href="#" name= "opera" class="easyui-linkbutton" style="width:80px"  onclick="show()" text="查看" iconCls="icon-add"></a>';
                    return str
                }
            }
            }
        ]],
        //点击行时响应事件
        onClickRow: function (index, row) {
            //根据部门的状态修改审核/未审核按钮的显示
            if (row.status == 1) {
                $("#changeAudit_btn").linkbutton({
                    text: "已审核"
                })
                $("#edit_btn").linkbutton("disable", true);
                $("#changeAudit_btn").linkbutton("disable", true);
            } else {
                $("#edit_btn").linkbutton("enable");
                $("#changeAudit_btn").linkbutton("enable");
                $("#changeAudit_btn").linkbutton({
                    text: "未审核"
                })
            }
        },
        onLoadSuccess: function () {
            $(".easyui-linkbutton").linkbutton({});
        }
    })

    //部门列表初始化-end
    //初始化新增和编辑的dialog
    $("#bill_dialog").dialog({
        widht: 400,
        height: 500,
        buttons: "#bb",
        draggable: true,
        resizable: true,
        closed: true
    })
    //订单明细的dialog
    $("#product_view").dialog({
        width: 800,
        height: 500,
        //是否可关闭的
        closed: true,
        modal: true,
        title: '添加商品'
    })
    //计算值
    $("#edit_tbody").on("change", "[tag=costPrice],[tag=number]", function () {
        var currentTr = $(this).closest('tr');
        var price = currentTr.find("[tag=costPrice]").val() || 0;
        var number = currentTr.find("[tag=number]").val() || 0;
        currentTr.find("[tag=amount]").html((price * number).toFixed(2));
    }).on("click", ".deleteItem", function () {
        var currentTr = $(this).closest("tr");
        currentTr.remove();
    })
    //为删除明细绑定事件
    $(".deleteItem").click(function () {
        //先判断一下,如果删除时只剩下一行,清空数据就好,如果还有就直接删除
        if ($("#itemTr tr").size() == 1) {
            //获取到第一行的tr
            var tr = $(this).closest("tr");
            //设置内容为空
            tr.find("input").val("");
            tr.find("span").text("");
        } else {
            //删除当前行
            $(this).closest("tr").remove();
        }
    })
    //添加商品
    $("#pro_datagrid").datagrid({
        fit: true,
        fitColumns: true,
        pagination: true,
        rownumbers: true,
        singleSelect: true,
        striped: true,
        buttons: "#bb",
        columns: [[
            {field: 'id', title:'id', hidden:true},
            {field: 'name', title: '商品名称', width: 100},
            {
                field: 'productCategory1', title: '一级分类', width: 100, formatter: function (value) {
                return value ? value.name : "";
            }
            },
            {
                field: 'productCategory2', title: '二级分类', width: 100, formatter: function (value) {
                return value ? value.name : "";
            }
            },
            {field: 'sn', title: '商品编码', width: 100},
            {field: 'costPrice', title: '商品单价', width: 100}
        ]],
        //值改变事件,点击发生改变
        onClickRow: function (index, row) {
            var copy = $("#itemTr tr:first").clone();
            copy.appendTo($("#edit_tbody"));
            copy.find("[tag=sn]").html(row.sn);
            copy.find("[tag=name]").html(row.name);
            copy.find("[tag=pid]").val(row.id);
            copy.find("[tag=costPrice]").val(row.costPrice);
            console.log(row);
            $("#product_view").dialog("close");

        }
    });
    bill_dialog.dialog({
        width: 1000,
        height: 600,
        buttons: "#orderBill_btns",
        closed: true,
        modal: true
    })

    /* var cmdObj = {
     fn:function(){
     alert(1);
     },
     name:"dafei"
     }
     cmdObj.fn();
     cmdObj["fn"]();
     cmdObj["name"];*/

    //同一管理响应函数
    var cmdObj = {
        //顶部工具栏的刷新
        reload: function () {
            bill_datagrid.datagrid("load");
        },
        //工具栏的编辑
        edit: function () {
            //是否选中row
            var row = bill_datagrid.datagrid("getSelected");
            if (!row) {
                $.messager.alert("温馨提示", "请选择要编辑的数据");
                return;
            }
            //清空上次操作的数据
            $("#bill_form").form("clear");
            $("#edit_tbody").html("");
            //处理供应商数据
            if (row.supplier) {
                row["supplier.id"] = row.supplier.id;
            }
            //回显选中的行
            $("#bill_form").form("load", row);

            //遍历每一个明细
            $.each(row.items, function (index, item) {
                var copy = $("#itemTr tr:first").clone();

                if (row.status) {
                    $(":input").prop("readOnly", true);
                    bill_dialog.dialog("setValue", "查看明细");
                } else {
                    $(":input").prop("readOnly", false);
                }
                copy.appendTo("#edit_tbody");
                copy.find("[tag=sn]").html(item.product.sn);
                copy.find("[tag=name]").html(item.product.name);
                copy.find("[tag=pid]").val(item.product.id);
                copy.find("[tag=costPrice]").val(item.costPrice);
                copy.find("[tag=amount]").html(item.amount);
                copy.find("[tag=remark]").val(item.remark);
                copy.find("[tag=number]").val(item.number);
            })
            //设置标题
            bill_dialog.dialog("setTitle", "订单编辑");
            //打开窗口
            bill_dialog.dialog("open");
        },
        addProduct: function () {
            $("#pro_datagrid").datagrid("load", '/product/queryProduct');
            //打开窗口
            $("#product_view").dialog("open");

        },
        //工具栏:添加
        add: function () {
            //清空上次操作的数据
            $("#bill_form").form("clear");
            //设置标题
            bill_dialog.dialog("setTitle", "新增订单");
            //打开窗口
            bill_dialog.dialog("open");
        },
        //工具栏:停业/营业 (在实际应用中,数据的价值非同小可,所以不要有删除操作)
        changeAudit: function () {
            //是否选中row
            var row = bill_datagrid.datagrid("getSelected");
            if (!row) {
                $.messager.alert("温馨提示", "请选择要操作的数据");
                return;
            }
            //重要操作:提示用户
            $.messager.confirm('确认', '您确认想要执行这个操作？', function (r) {
                if (r) {
                    //确定要进行操作
                    //修改选中行的状态(与原来相反)
                    //发请求修改原先状态值
                    $.get("/orderBill/changeAudit", {id: row.id}, function (data) {
                        if (data.success) {
                            $.messager.alert("温馨提示","审核成功");
                            //修改成功就刷新列表

                        } else {
                            $.messager.alert("温馨提示", data.errorMsg);
                        }
                        bill_datagrid.datagrid("reload");
                    })
                }
            });
        },
        //底部按钮:保存
        save: function () {
            //获取明细的值
            $.each($("#edit_tbody tr"), function (index, item) {
                $(item).find("[tag=pid]").prop("name", "items[" + index + "].product.id");
                $(item).find("[tag=costPrice]").prop("name", "items[" + index + "].costPrice");
                $(item).find("[tag=number]").prop("name", "items[" + index + "].number");
                $(item).find("[tag=remark]").prop("name", "items[" + index + "].remark");
            })
            //默认是保存请求
            var url = "orderBill/save";
            var billId = $("#billId").val();
            if (billId) {
                //回显的billId有值则是update
                url = "orderBill/update";
            }
            $('#bill_form').form('submit', {
                url: url,
                //表单提交成功后
                success: function (data) {
                    var data = $.parseJSON(data);
                    if (!data.success) {
                        $.messager.alert('温馨提示', data.errorMsg);
                        //刷新列表
                        bill_datagrid.datagrid("reload");
                        //关闭当前对话框
                       bill_dialog.dialog("close");
                    } else {
                        $.messager.alert('温馨提示', data.errorMsg);
                    }

                }
            });
        },
        //底部按钮:取消
        cancel: function () {
            bill_dialog.dialog("close");
        }
    } //end
    //调用cmdObj
    $("a[data-cmd]").click(function () {
        var cmd = $(this).data('cmd');
        cmdObj[cmd]();
    })
})

function show() {
    var row = $("#bill_datagrid").datagrid("getSelected");
    if(!row){
        $.messager.alert("温馨提示","请选中要查看的那一行");
        return;
    }
  /*  if (!row) {
        $.messager.alert('温馨提示', '请选中一条数据!', 'warning');
        return;
    }*/
    //清空表单数据
    $("#bill_form").form("clear");
    $("#edit_tbody").html("");
    //处理供应商数据
    if (row.supplier) {
        row["supplier.id"] = row.supplier.id;
    }
    //回显数据
    $("#bill_form").form("load", row);
    $.each(row.items, function (index,item) {
        var copy = $("#itemTr tr:first").clone();
        console.log(copy);
        if(row.status){
            $(":input").prop("readOnly",true);
        }else{
            $(":input").prop("readOnly",false);
        }
        copy.appendTo("#edit_tbody");
        copy.find("[tag=sn]").html(item.product.sn);
        copy.find("[tag=name]").html(item.product.name);
        copy.find("[tag=pid]").val(item.product.id);
        copy.find("[tag=costPrice]").val(item.costPrice);
        copy.find("[tag=amount]").html(item.amount);
        copy.find("[tag=remark]").val(item.remark);
        copy.find("[tag=number]").val(item.number);
    })
    $("#bill_dialog").dialog("setTitle","查看详情");
    //设置标题
    //打开弹窗
    $("#bill_dialog").dialog("open");


}

